package com.atguigu.yygh.apartment.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.yygh.apartment.service.ChamberService;
import com.atguigu.yygh.apartment.service.StudentInfoService;
import com.atguigu.yygh.apartment.utils.KMeans;
import com.atguigu.yygh.common.helper.HttpRequestHelper;
import com.atguigu.yygh.common.result.Result;
import com.atguigu.yygh.apartment.config.*;
import com.atguigu.yygh.model.hosp.ApartmentInfo;
import com.atguigu.yygh.model.hosp.StudentInfo;
import com.atguigu.yygh.model.user.StudentDetail;
import com.atguigu.yygh.model.user.UserInfo;
import com.atguigu.yygh.vo.cmn.WenJuan;
import com.atguigu.yygh.vo.cmn.wenJuanEeVo;
import com.atguigu.yygh.vo.hosp.ChamberVo;
import com.atguigu.yygh.vo.user.UserInfoVo;
import com.jscq.stuDetail.client.StuDetailFeignClient;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@RestController
@RequestMapping("/admin/apartment/chamber")
//@CrossOrigin
public class ChamberController {
    @Autowired
    private ChamberService chamberService;

    @Autowired
    private StudentInfoService studentInfoService;

    @Autowired
    private StuDetailFeignClient stuDetailFeignClient;



    //根据宿舍编号，查询所有寝室
    @ApiOperation(value = "查询所有寝室列表")
    @GetMapping("getChamberList/{apartmentCode}")
    public Result getChamberList(@PathVariable String apartmentCode){
       List<ChamberVo> list = chamberService.findChamberTree(apartmentCode);
       return Result.ok(list);
    }

    @ApiOperation(value = "寝室详情")
    @GetMapping("getStudentInfoDetail/{apartmentCode}/{chamberCode}")
    public Result getStudentInfoDetail(@PathVariable String apartmentCode,
                                       @PathVariable String chamberCode){
        //System.out.println("apartmentCode:"+apartmentCode);
        //System.out.println("chamberCode:"+chamberCode);
        List<StudentInfo> list = studentInfoService.getDetailStudentInfo(apartmentCode, chamberCode);
        System.out.println("list:"+list.toString());
        return Result.ok(list);
    }
    @ApiOperation(value = "保存寝室")
    @PostMapping("saveChamber/{apartmentCode}")
    public Result saveChamber(@PathVariable String apartmentCode,
                              @RequestBody String jsonData){
        JSONArray jsonArray = new JSONArray();
        if(!jsonData.startsWith("[")) {
            JSONObject jsonObject = JSONObject.parseObject(jsonData);
            jsonArray.add(jsonObject);
        } else {
            jsonArray = JSONArray.parseArray(jsonData);
        }

        for(int i=0, len=jsonArray.size(); i<len; i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);

            Map<String, Object> paramMap = new HashMap<>();
            paramMap.put("apartmentCode", apartmentCode);
            paramMap.put("chamberCode", jsonObject.getString("chamberCode"));
            paramMap.put("chamberName", jsonObject.getString("chamberName"));
            paramMap.put("intro", jsonObject.getString("intro"));
            paramMap.put("bigcode", jsonObject.getString("bigcode"));
            paramMap.put("bigname", jsonObject.getString("bigname"));
            paramMap.put("timestamp", HttpRequestHelper.getTimestamp());

            //paramMap.put("sign",HttpRequestHelper.getSign(paramMap, this.getSignKey()));
            chamberService.save(paramMap);
            List<StudentInfo> list = new ArrayList<>();
            for (int j = 0;j<6;j++){
                StudentInfo studentInfo = new StudentInfo();
                if (j==0){
                    studentInfo.setTitle("舍长");
                }else {
                    studentInfo.setTitle("成员");
                }
                studentInfo.setIsDeleted(0);
                studentInfo.setStatus(1);
                studentInfo.setApartmentCode(apartmentCode);
                studentInfo.setChamberCode(jsonObject.getString("chamberCode"));
                studentInfo.setStuName("");
                studentInfo.setPhone("");
                studentInfo.setStuCode("");
                studentInfo.setBedId(apartmentCode+jsonObject.getString("chamberCode")+j);
                studentInfoService.save(studentInfo);
            }
        }

        return Result.ok();
    }

    @ApiOperation(value = "学生入住")
    @GetMapping("addStudentInfoToChamber/{bedId}/{stuCode}")
    private Result addStudentInfoToChamber(@PathVariable String bedId,
                                           @PathVariable String stuCode){

        StudentDetail studentDetail = stuDetailFeignClient.getStuDetail(stuCode);
        Result result=studentInfoService.addStudent(bedId,studentDetail);
        return result;
    }

    @ApiOperation(value = "批量入住")
    @PostMapping("addStudentInfosToChamber/{bedId}")
    private Result addStudentInfosToChamber(@PathVariable String bedId,
                    @RequestBody String studentInfos){

    //String test = "学号:1912120220 姓名:张三4,学号:1912120227 姓名:张三11,学号:1912120247 姓名:张三31,学号:1912120250 姓名:张三34,学号:1912120261 姓名:张三45";
    List<UserInfoVo> userInfoVos = new ArrayList<>();

    String decodedData = studentInfos;

    try {
        decodedData= URLDecoder.decode(studentInfos, "UTF-8");
        if (decodedData.endsWith("=")) {
            decodedData = decodedData.substring(0, decodedData.length() - 1);
        }
        System.out.println("stuInfo:"+decodedData);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String[] userInfoStrings = decodedData.split(",");
    
        // 遍历分割后的字符串数组
        int i = 0;
        for (String userInfoString : userInfoStrings) {
            // 提取学号和姓名

            String stuCode = userInfoString.substring(userInfoString.indexOf("学号:") + 3, userInfoString.indexOf(" 姓名:"));
            String name = userInfoString.substring(userInfoString.indexOf("姓名:") + 3);

            // 创建 UserInfoVo 对象并存储到列表中
            UserInfoVo userInfoVo = new UserInfoVo();
            userInfoVo.setStuCode(stuCode);
            userInfoVo.setName(name);
            userInfoVo.setBedId(bedId+i);
            userInfoVos.add(userInfoVo);
            i++;
        }
        Result result=studentInfoService.addStudentByStuCodeAndName(userInfoVos);
        return Result.ok(result);
    }
    @ApiOperation(value = "学生退宿")
    @GetMapping("deleteStudentInfoToChamber/{bedId}")
    private Result deleteStudentInfoToChamber(@PathVariable String bedId){

        studentInfoService.deleteStudent(bedId);
        return Result.ok();
    }

    @ApiOperation(value = "删除床位")
    @GetMapping("removeChamber/{bedId}")
    private Result removeChamber(@PathVariable String bedId){

        studentInfoService.removeChamber(bedId);
        return Result.ok();
    }

    //导入表格数据
    @PostMapping("KMeans")
    public Result KMeans(MultipartFile file, HttpServletResponse response,Integer maxIter) {
        response.setHeader("Access-Control-Allow-Origin", "*");
        System.out.println("maxIter:" + maxIter);
        //File fileMale = new File("C:\\Users\\pc\\Desktop\\男生.xlsx");
        try {
            //System.out.println("1111111");
            System.out.println("file:"+file.getInputStream());
            List<wenJuanEeVo> list = EasyExcel.read(file.getInputStream()).head(wenJuanEeVo.class).sheet().doReadSync();
            //System.out.println("file:"+file.getInputStream());
            double[][] dataArray = new double[list.size()][6]; // 创建二维数组，行数为数据列表的长度，列数为7
            // 遍历数据列表，将每个数据的属性值放入数组中
            for (int i = 0; i < list.size(); i++) {
                WenJuan wenJuan = new WenJuan();
                BeanUtils.copyProperties(list.get(i), wenJuan);
                dataArray[i][0] = wenJuan.getIsSmoke();
                dataArray[i][1] = wenJuan.getSleepBetween();
                dataArray[i][2] = wenJuan.getIsSleep();
                dataArray[i][3] = wenJuan.getLikeSports();
                dataArray[i][4] = wenJuan.getIsTwo();
                dataArray[i][5] = wenJuan.getLikeEv();
            }
            int capacity = 6;//宿舍容量
            int n = dataArray.length; // 样本数
            int k = n % capacity == 0 ? n / capacity : n / capacity + 1; // 簇的个数
            int m = dataArray[0].length; // 样本维度

            KMeans kMeans = new KMeans(k, n, m, maxIter, dataArray, capacity);
            kMeans.run();
            int[][] clusters = new int[k][n];
            for (int i = 0; i < n; i++) {
                int clusterIndex = kMeans.getLabels()[i]; // 获取该样本所属的簇编号
                clusters[clusterIndex][i] = 1; // 将该样本的聚类结果存储到对应的簇中
            }
            List<List<String>> stuList = new ArrayList<>();

            for (int i = 0; i < k; i++) {

                List<String> temp = new ArrayList<>();
                for (int j = 0; j < n; j++) {
                    if (clusters[i][j] == 1) {
                        //System.out.print(list.get(j).getStuNo() + " ");
                        temp.add("学号:"+list.get(j).getStuNo()+" 姓名:"+list.get(j).getStuName());
                    }
                }
                stuList.add(temp);

            }
//            for (int i = 0; i < stuList.size(); i++) {
//                System.out.println("簇："+i+"有学生"+stuList.get(i));
//            }
            return Result.ok(stuList);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return Result.fail();
    }
}
